package com.oim.common.util;

import com.oim.core.business.constant.Setting;
import javafx.event.EventType;
import javafx.scene.control.MenuItem;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

import java.util.function.Consumer;

public class CommonUtil {

    /**
     * 快捷键
     *
     * @param e
     * @param consumer
     */
    public static void sendByShortKey(KeyEvent e, Consumer consumer) {
        KeyCode code = e.getCode();  //快捷键发送
        if (Setting.shortKey == 0) {
            if (!(e.isShiftDown() || e.isControlDown()) && code == KeyCode.ENTER) {
                consumer.accept(e);
                e.consume();
            }
        } else {
            if (e.isControlDown() && code == KeyCode.ENTER) {
                consumer.accept(e);
                e.consume();
            }
        }
    }

    public static MenuItem buildCopyMenuItem(Consumer<KeyEvent> consumer) {
        MenuItem mi = new MenuItem("复制");
        mi.setOnAction(a -> {
            KeyEvent ke = createKeyEvent(KeyEvent.KEY_PRESSED, KeyCode.C, "", "", false, true, false, false);
            consumer.accept(ke);
            ke = createKeyEvent(KeyEvent.KEY_RELEASED, KeyCode.C, "", "", false, true, false, false);
            consumer.accept(ke);
        });
        return mi;
    }

    public static KeyEvent createKeyEvent(
            EventType<? extends KeyEvent> eventType,
            KeyCode code, String character, String text,
            boolean shiftDown, boolean controlDown,
            boolean altDown, boolean metaDown) {
        return new KeyEvent((EventType<KeyEvent>) eventType, character, text, code, shiftDown, controlDown, altDown, metaDown);
    }

    public static MenuItem buildClearMenuItem(Consumer<String> consumer) {
        MenuItem clear = new MenuItem("清屏");
        String js = createClearBodyJavaScript();
        clear.setOnAction(actionEvent -> {
            consumer.accept(js);
        });
        return clear;
    }

    private static String createClearBodyJavaScript() {
        StringBuilder js = new StringBuilder();
        js.append("function clearBody(){\n");
        js.append("    document.body.innerHTML=\"\";\n");
        js.append("}");
        js.append("clearBody();");
        String jsInsertHtml = js.toString();
        return jsInsertHtml;
    }
}
